<template>
    <div class="login">
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title">运维管理系统</h3>
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              type="text"
              size="large"
              auto-complete="off"
              placeholder="账号"
          >
          <template #prefix><svg-icon icon="user"/></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              size="large"
              auto-complete="off"
              placeholder="密码"
              show-password
          >
          <template #prefix><svg-icon icon="lock"/></template>
          </el-input>
        </el-form-item>
  
  
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <el-form-item style="width:100%;">
          <el-button
              size="large"
              type="primary"
              style="width:100%;"
              @click.prevent="handleLogin"
          >
            <span>登 录</span>
  
          </el-button>
  
        </el-form-item>
      </el-form>
      <!--  底部  -->
      <div class="el-login-footer">
        <span>Copyright 2013-2025 <a href="http://www.ywadmin.com" target="_blank">ywadmin.com</a> 版权所有.</span>
      </div>
    </div>
  </template>
  
  <script setup>
  import { User, Lock } from '@element-plus/icons-vue'
  import { ref } from 'vue'
  import requestUtil from '@/util/request'
  import { ElMessage } from 'element-plus'
  import Cookies from 'js-cookie'
  import { encrypt, decrypt } from '@/util/aesEncrypt'
  import router from '@/router'

  const loginForm = ref({
    username: '',
    password: '',
    rememberMe: false
  })

  const loginRef = ref(null)

  const loginRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  }

  const handleLogin = () => {
    loginRef.value.validate(async(valid) => {
      if (valid) {
        try {
          // 加密密码 - 使用临时变量，不修改原始表单数据
          const encryptedPassword = encrypt(loginForm.value.password)
          
          // 创建新的登录数据对象
          const loginData = {
            username: loginForm.value.username,
            password: encryptedPassword,
            rememberMe: loginForm.value.rememberMe
          }
          
          const result = await requestUtil.post("system/login", loginData)
          const token = result.token
          const refreshToken = result.refresh  // 获取刷新令牌
          const menuList = result.data
          const permissions = result.permissions || []  // 获取按钮权限列表
          const currentUser = result.user
          currentUser.roles = result.roles
          window.sessionStorage.setItem("token", token)
          window.sessionStorage.setItem("refresh", refreshToken)  // 存储刷新令牌
          window.sessionStorage.setItem("menuList", JSON.stringify(menuList))
          window.sessionStorage.setItem("permissions", JSON.stringify(permissions))  // 存储权限列表
          window.sessionStorage.setItem("currentUser", JSON.stringify(currentUser))

          ElMessage.success(result.msg)
          // 如果选择记住密码，将token保存到Cookies，默认30天
          if (loginForm.value.rememberMe) {
            Cookies.set("username", loginForm.value.username, { expires: 30 })
            // 保存加密后的密码到Cookie
            Cookies.set("password", encryptedPassword, { expires: 30 })
            Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 })
            Cookies.set("token", token)
            Cookies.set("refresh", refreshToken)  // 同时保存刷新令牌
          } else {
            Cookies.remove("username")
            Cookies.remove("password")
            Cookies.remove("rememberMe")
          }
          // 跳转到首页
          router.replace({
            name: 'home'
          })

        } catch (error) {
          ElMessage.error("登录失败！")
          console.error(error)
        }
      } else {
        // ElMessage.error("表单验证失败！")
        console.log('验证失败')
      }
    })
  }

  function getCookie() {
    const username = Cookies.get("username")
    const password = Cookies.get("password")
    const rememberMe = Cookies.get("rememberMe")
    const token = Cookies.get("token")
    const refreshToken = Cookies.get("refresh")
  
    // 如果有存储的密码，先解密并确保移除所有可能的空字符
    let decryptedPassword = ''
    if (password) {
      try {
        decryptedPassword = decrypt(password).replace(/\0/g, '')
        // console.log("从Cookie解密的密码长度:", decryptedPassword.length)
      } catch (e) {
        console.error("密码解密失败:", e)
        decryptedPassword = ''
      }
    }
  
    loginForm.value = { 
      username: username == undefined ? loginForm.value.username : username, 
      password: password == undefined ? loginForm.value.password : decryptedPassword, 
      rememberMe: rememberMe == undefined ? loginForm.value.rememberMe : Boolean(rememberMe) 
    }
  }

  getCookie();

  
  </script>
  
  <style lang="scss" scoped>
  a{
    color:white
  }
  .login {
    display: flex; /* flex布局自适应 */
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    height: 100%;
    background-image: url("../assets/images/login-background.jpg");
    background-size: cover;
  }
  .title {
    font-size: 26px;
    font-weight: 700;
    margin: 0px auto 30px auto;
    text-align: center;
    color: #707070;
  }
  
  .login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 5px 25px;
  
    .el-input {
      height: 40px;
  
  
  
      input {
        display: inline-block;
        height: 40px;
      }
    }
    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 0px;
    }
  
  }
  .login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
  }
  .login-code {
    width: 33%;
    height: 40px;
    float: right;
    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }
  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
  }
  .login-code-img {
    height: 40px;
    padding-left: 12px;
  }
  </style>
  